package script

import (
	"game/core"

	"github.com/hajimehoshi/ebiten/v2"
	"github.com/solarlune/resolv"
)

type Bullet struct {
	core.Sprite
	ProjectileMovement *core.ProjectileMovement
}

func NewBullet(position *resolv.Vector) *Bullet {

	b := &Bullet{
		Sprite: core.Sprite{
			Position: position,
			Scale:    &resolv.Vector{X: 0.5, Y: 0.5},
			Image:    BulletImg,
		},
	}
	position.Y -= b.GetWH().Y - 20
	b.SetPosition(*position)
	wh := b.GetWH()
	b.Collision = resolv.NewRectangle(b.GetCenter().X, b.GetCenter().Y, wh.X/5, wh.Y/2)
	b.Collision.Tags().Set(core.TagPlayerBullet)

	b.ProjectileMovement = core.NewProjectileMovement(b, core.ProjectileMovementOption{Lifetime: 2})

	// 加载音频文件
	BulletSound.Rewind()
	BulletSound.Play()
	return b
}

func (b *Bullet) Update(dt float64) error {
	b.ProjectileMovement.MoveVec(resolv.NewVector(0, -10))

	b.Collision.IntersectionTest(resolv.IntersectionTestSettings{
		TestAgainst: b.Collision.SelectTouchingCells(1).FilterShapes(),
		OnIntersect: func(set resolv.IntersectionSet) bool {
			if set.OtherShape.Tags().Has(core.TagWall) {
				b.Destory()
			}
			return true
		},
	})
	return nil
}

func (b *Bullet) Draw(screen *ebiten.Image) {
	op := &ebiten.DrawImageOptions{}
	op.GeoM.Scale(b.Scale.X, b.Scale.Y)
	op.GeoM.Translate(b.Position.X, b.Position.Y)

	screen.DrawImage(b.Image, op)
}
